package com.example.shushiyunsst.util.push.helper;

import com.alibaba.fastjson.JSON;
import com.example.library_common.utils.digest.DigestUtils;
import com.example.shushiyunsst.util.MD5Util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class PushClient {
    public PushClient() {
        HttpLoggingInterceptor  HttpLogging=new HttpLoggingInterceptor();
        HttpLogging.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = new OkHttpClient.Builder().addInterceptor(HttpLogging).build();

    }

    // The user agent
    protected final String USER_AGENT = "Mozilla/5.0";

    // This object is used for sending the post request to Umeng
//    protected HttpClient client = new DefaultHttpClient();
	private  OkHttpClient client = new OkHttpClient();

    // The host
    protected static final String host = "http://msg.umeng.com";

    // The upload path
    protected static final String uploadPath = "/upload";

    // The post path
    protected static final String postPath = "/api/send";

    public boolean send(UmengNotification msg) throws Exception {
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        msg.setPredefinedKeyValue("timestamp", timestamp);
        String url = host + postPath;
        String postBody = msg.getPostBody();
        String appMasterSecret = msg.getAppMasterSecret();
//        String sign = MD5Util.md5Hex(("POST" + url + postBody + appMasterSecret));
        String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret));
        url = url + "?sign=" + sign;
        RequestBody mRequestBody= RequestBody.create(postBody.getBytes("UTF-8"));
        Request request =new Request.Builder()
                .url(url)
                .addHeader("User-Agent", USER_AGENT)
                .post(mRequestBody)
                .build();

        Response response = client.newCall(request).execute();
        if (response.isSuccessful()){
            ResponseBody body = response.body();
            if (body!=null){
                String string = body.string();
                System.out.println(string);
            }

        }
//        String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
//        url = url + "?sign=" + sign;
//        HttpPost post = new HttpPost(url);
//        post.setHeader("User-Agent", USER_AGENT);
//        StringEntity se = new StringEntity(postBody, "UTF-8");
//        post.setEntity(se);
//        // Send the post request and get the response
//        HttpResponse response = client.execute(post);
//        int status = response.getStatusLine().getStatusCode();
//        System.out.println("Response Code : " + status);
//        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
//        StringBuffer result = new StringBuffer();
//        String line = "";
//        while ((line = rd.readLine()) != null) {
//            result.append(line);
//        }
//        System.out.println(result.toString());
//        if (status == 200) {
//            System.out.println("Notification sent successfully.");
//        } else {
//            System.out.println("Failed to send the notification!");
//        }
        return true;
    }

    // Upload file with device_tokens to Umeng
    public String uploadContents(String appkey, String appMasterSecret, String contents) throws Exception {
        // Construct the json string
        JSONObject uploadJson = new JSONObject();
        uploadJson.put("appkey", appkey);
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        uploadJson.put("timestamp", timestamp);
        uploadJson.put("content", contents);
        // Construct the request
        String url = host + uploadPath;
        String postBody = uploadJson.toString();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
//        String sign = MD5Util.md5Hex(("POST" + url + postBody + appMasterSecret));
        url = url + "?sign=" + sign;
        RequestBody mRequestBody= RequestBody.create(postBody.getBytes("UTF-8"));
		Request request =new Request.Builder()
				.url(url)
				.addHeader("User-Agent", USER_AGENT)
				.post(mRequestBody)
				.build();

        Response response = client.newCall(request).execute();
        String fileId ="";
        if (response.isSuccessful()){
            ResponseBody body = response.body();
            if (body!=null){
                String string = body.string();
                com.alibaba.fastjson.JSONObject object = JSON.parseObject(string);
                fileId=object.getString("file_id");
            }

        }
        return fileId;
//        HttpPost post = new HttpPost(url);
//        post.setHeader("User-Agent", USER_AGENT);
//        StringEntity se = new StringEntity(postBody, "UTF-8");
//        post.setEntity(se);
//        // Send the post request and get the response
//        HttpResponse response = client.execute(post);
//        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
//        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
//        StringBuffer result = new StringBuffer();
//        String line = "";
//        while ((line = rd.readLine()) != null) {
//            result.append(line);
//        }
//        System.out.println(result.toString());
//        // Decode response string and get file_id from it
//        JSONObject respJson = new JSONObject(result.toString());
//        String ret = respJson.getString("ret");
//        if (!ret.equals("SUCCESS")) {
//            throw new Exception("Failed to upload file");
//        }
//        JSONObject data = respJson.getJSONObject("data");
//        String fileId = data.getString("file_id");
        // Set file_id into rootJson using setPredefinedKeyValue

//        return fileId;
    }

}
